import re
import uuid

from mongoengine import QuerySet, Q

# def select_policy(queryset, id=None, title=None, keywords=None, introduction=None, unit=None, province=None, data=None):
def select_policy(queryset, id=None, info=None, unit=None, province=None, data=None):
    """
    设置搜索框检索结果
    搜索框有两个，但是搜索框输入内容不同,这里使用一个函数完成两个搜索框的结果呈现》
    第一个搜索框: 关键词(标题、简介和关键词)、发布单位；
    第二个搜索框：关键词(标题、简介和关键词)、发布单位、时间和省份。
    """
    if not (id or info or unit or province or data):
        return None
    result = queryset
    if id is not None:
        result = result.filter(id=id)
    if info is not None:
        re_keywords = '.*' + info + '.*'
        result = result(Q(title__icontains=info) | Q(keywords=re.compile(re_keywords, re.IGNORECASE)) | Q(introduction__icontains=info))
    if unit is not None:
        result = result.filter(unit__icontains=unit)
    if province is not None:
        result = result.filter(province=province)
    if data is not None:
        result = result.filter(data__icontains=data)
    return result

def select_guide(queryset, id=None, level=None, name=None, unit=None):
    if not (id or level or name or unit):
        return None
    result = queryset
    if id is not None:
        result = result.filter(id=id)
    if level is not None:
        result = result.filter(level__icontains=level)
    if name is not None:
        result = result.filter(name__icontains=name)
    if unit is not None:
        result = result.filter(unit__icontains=unit)
    return result

def select_awards(queryset, id=None, awards=None, topical=None):
    if not (id or awards or topical):
        return None
    result = queryset
    if id is not None:
        result = result.filter(id=id)
    if awards is not None:
        result = result.filter(awards__icontains=awards)
    # if recommendUnit is not None:
    #     result = result.filter(recommendUnit__icontains=recommendUnit)
    if topical is not None:
        result = result.filter(topical__icontains=topical)
    #if unit is not None:
        # result = result.filter(unit__icontains=unit)
        #re_unit = '.*' + unit + '.*'
        #result = result.filter(unit=re.compile(re_unit, re.IGNORECASE))
    return result
